/**
 * 公共配置&路由
 * 2023/5/5
 */

const express = require("express");
const router = express.Router();
const Result = require("../utils/Result");
const { v4: uuidv4 } = require('uuid');
const iconv = require('iconv-lite');
router.get('/', function (req, res) {
    res.send('公共配置')
})
let basefileUrl = __dirname + "/../file/"
router.post('/fileUpload', (req, res) => {
    console.log(req.files);
    if (req.files == null) {
        return new Result('请上传文件').fail(res)
    }
    
    let files = req.files.file;
    // console.log(files instanceof Array);
    if (files instanceof Array) {
        //多文件
        fileList(files).then(v=>res.send({ massage: '上传成功！', urls:v }))
    } else {
        //单文件files.name
        let fileName = files.name;
        let fileUrl = basefileUrl + fileName; // 文件名
        files.mv(fileUrl, function (err) {
            if (err)
                return res.status(500).send(err);
            new Result([{uid:uuidv4(),status: 'done',name:fileName,url:"/file/" + fileName}],'上传成功！').success(res)
        })
    }
})

function fileList(files) {
    
    return new Promise((resolve, reject) => {
        let urls = []
        files.forEach((file,i) => {
            console.log('正在上传' + file.name + '...');
            // 设定文件的保存路径
            let fileUrl = basefileUrl + file.name; // 文件名
            file.mv(fileUrl, function (err) {
                if (err)
                    return reject();
                urls.push({ name: file.name, url: "/file/" + file.name })
                if (i == files.length-1) {
                    resolve(urls)
                }
            })
        });
    })
}

module.exports = router;